<?php

namespace Frieza\Modules\Tag\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Category;
use Doraemon\model\Tag\NewTagType as mTagTypeList;
use Doraemon\service\Tag\TagTypeList as sTagTypeList;


class TagTypeController extends Controller
{
    const PAGE_SIZE = 50;

    public function list(Content $content)
    {
        return $content
            ->header('标签分类管理')
            ->breadcrumb(
                ['text' => '分类列表', 'url' => '/admin/tag/type/list']
            )
            ->body($this->listAction());
    }

    private function listAction()
    {

        $tagTypeInfo = sTagTypeList::getList();
        $gridModel = new pGridDataModel($tagTypeInfo);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->fixColumns(2, -2);
            $grid->disableFilter();

            $grid->column('id');
            $grid->column('name', '一级分类');
            $grid->column('sons', '二级分类')->display(function () {
                $format = [];
                if ($this->sons) {
                    foreach ($this->sons as $_son) {
                        $format[] = $_son['name'];
                    }
                }
                return $format;
            })->label('default');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '暂无';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
        });

        return $listGrid->render();
    }

    public function editTagtype(Request $request, $id = 0, Content $content)
    {
        $tab = new tab();
        $tab->add('编辑分类', $this->editOneAction($id, strpos($request->url(), 'create')));
        if (!strpos($request->url(), 'create')) {
            $tab->add('二级分类', $this->listTwoAction($id));
        }

        return $content
            ->header('分类管理')
            ->breadcrumb(
                ['text' => '分类列表', 'url' => '/tag/type/list'],
                ['text' => '编辑分类']
            )
            ->body($tab);
    }

    private function editOneAction($id, $isCreate = false)
    {
        if ($isCreate) {
            $form = new Form();
            $form->text('name', '一级分类')->required('一级分类不能为空');
        } else {
            $info = mTagTypeList::getInfoById($id);
            $form = new Form($info[0]);
            $form->hidden('id');
            $form->text('name', '一级分类')->required('一级分类不能为空');
        }

        $form->action('/admin/tag/type/onesave');
        return $form;
    }

    public function saveOneTagtype(Request $request)
    {
        $params = [
            'name' => $request->input('name', ''),
            'id'   => $request->input('id', 0),
        ];
        // 判断要添加的类名是否存在
        $isHaveTagtype = sTagTypeList::haveTagtype($params);
        if ($isHaveTagtype) {
            $error = new MessageBag([
                'title' => '分类已存在',
            ]);
            return back()->with(compact('error'));
        }

        $res = sTagTypeList::saveOneTagtype($params);

        if ($res) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/tag/type/list')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败',
            ]);

            return back()->with(compact('error'));
        }
    }
    /**
     * 二级分类列表
     *
     * @param [int] $id
     * @return void
     */
    private function listTwoAction($id)
    {
        $tagTypeInfo = sTagTypeList::getList($id);
        $gridModel = new pGridDataModel($tagTypeInfo);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->disableFilter();

            $grid->column('id');
            $grid->column('name', '二级分类');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '暂无';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
        });

        return $listGrid->render();
    }

    public function editTwoTagtype(Request $request, $pid = 0, $id = 0, Content $content)
    {
        return $content
            ->header('分类管理')
            ->breadcrumb(
                ['text' => '分类列表', 'url' => '/tag/type/list'],
                ['text' => '编辑分类']
            )
            ->body($this->editTwoAction($pid, $id, strpos($request->url(), 'create')));
    }
    /**
     * 编辑二级分类
     *
     * @param [array] $where
     * @param [type] $id
     * @param boolean $isCreate
     * @return void
     */
    public function editTwoAction($pid, $id, $isCreate = false)
    {
        $pInfo = sTagTypeList::getTagById($pid);
        if ($isCreate) {
            $infos = [
                'parent_id' => $pid,
                'pname'     => $pInfo['name'],
            ];
            $form = new Form($infos);
            $form->hidden('parent_id');
            $form->text('pname', '一级分类')->disable();
            $form->text('name', '二级分类');
        } else {
            $pInfo = mTagTypeList::get('*', ['id' => $pid]);
            $sonInfo = mTagTypeList::get('*', ['id' => $id]);
            $infos = [
                'pname' => $pInfo['name'],
                'name' => $sonInfo['name'],
                'id' => $sonInfo['id'],
            ];
            $form = new Form($infos);
            $form->hidden('id');
            $form->text('pname', '一级分类')->disable();
            $form->text('name', '二级分类');
        }
        $form->action('/admin/tag/type/list/twosave');
        return $form->render();
    }

    /**
     * 保存二级分类信息
     *
     * @param Request $request
     * @return void
     */
    public function saveTwoTagtype(Request $request)
    {
        $params = [
            'id' => $request->input('id', 0),
            'name' => $request->input('name', ''),
            'parent_id' => $request->input('parent_id', 0),
        ];
        $res = sTagTypeList::saveTwoTagtype($params);
        if ($res) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/tag/type/list')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败',
            ]);

            return back()->with(compact('error'));
        }
    }
    /**
     * 删除一级分类
     *
     * @param [int] $Id
     * @return void
     */
    public function delTagtype($id)
    {
        $params['id'] = $id;
        // 下边还有子类的时候   不允许删除
        $isHaveSon = sTagTypeList::haveSon($id);
        if ($isHaveSon) {
            return response()->json([
                'status' => false,
                'message' => "还有子类，不允许删除",
            ]);
        } else {
            $result = sTagTypeList::delTagtype($id);
        }

        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }

    /**
     * 删除二级分类
     *
     * @param [int] $Id
     * @return void
     */
    public function delTwoTagtype($pid, $id)
    {

        $result = sTagTypeList::delTagtype($id);

        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }
}
